<!--
  用户管理-企业用户-企业用户列表
 -->
<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <!--  缺少姓名搜索 -->
      <el-form-item label="姓名" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入企业申请人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="认证状态" prop="authorizedStatus">
        <el-select
          v-model="queryParams.authorizedStatus"
          placeholder="请选择企业状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in this.getDictDatas(DICT_TYPE.AUTHORIZED_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- todo 手机号搜索报错 -->
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- todo 调用企业角色接口，查看符合角色的企业用户 -->
      <el-form-item label="账号类型" prop="roleType">
        <el-select
          v-model="queryParams.roleType"
          placeholder="请选择账号类型"
          clearable
          size="small"
        >
          <el-option label="企业管理员" value="tenant_admin">企业管理员</el-option>
          <el-option label="普通员工" value="company_user">普通员工</el-option>
          <el-option label="游客" value="gust">游客</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
        >搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="createNewCompany(false)"
        >新增企业</el-button>
      </el-col>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="createNewCompany(true)"
      >新增白名单企业</el-button>
      <el-button
        v-if="isSuperAdmin"
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="exportDate()"
      >导出企业用户信息</el-button>
    </el-row>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" type="index" />
      <el-table-column label="姓名" align="center" prop="nickname" />
      <el-table-column label="企业名称" align="center" prop="companyName" />
      <el-table-column label="部门" align="center" prop="dept" />
      <el-table-column label="认证状态" align="center" prop="authorizedStatus">
        <template slot-scope="scope">
          <span>{{
            scope.row.authorizedStatus === null
              ? "--"
              : authStatus[scope.row.authorizedStatus]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phoneNumber">
        <template slot-scope="scope">
          {{ scope.row.phoneNumber | decodeMobileWithSecret }}
        </template>
      </el-table-column>
      <el-table-column
        label="注册时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否白名单" align="center" prop="unrealFlag">
        <template slot-scope="scope">
          <span>{{
            scope.row.unrealFlag === null
              ? "否"
              : ["否", "是"][scope.row.unrealFlag]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最近登录"
        align="center"
        prop="loginDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.companyId !== null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheck(scope.row)"
          >查看</el-button>
          <el-button
            v-if="scope.row.companyId !== null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新建-步骤一，填写用户信息 -->
    <el-dialog
      :title="title"
      :visible.sync="openUserDialog"
      width="50%"
      append-to-body
    >
      <p>填写用户信息</p>
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="applyUserName">
          <el-input v-model="userForm.applyUserName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门" prop="dept">
          <el-input v-model="userForm.dept" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位" prop="job">
          <el-input v-model="userForm.job" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="座机号" prop="tel">
          <el-input v-model="userForm.tel" placeholder="请输入座机号" />
        </el-form-item>
        <el-form-item label="邮箱号" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱号" />
        </el-form-item>
        <el-form-item label="账户类型">
          <el-select disabled value="1">
            <el-option value="1" label="企业管理员">企业管理员</el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="openCompanyWhite" label="是否白名单">
          <el-select disabled :value="1">
            <el-option :value="1" label="是">是</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUserForm">下一步</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新建-步骤二，填写企业信息 -->
    <el-dialog
      :title="title"
      :visible.sync="openCompanyDialog"
      width="50%"
      append-to-body
    >
      <p>填写企业信息</p>
      <el-form
        ref="companyForm"
        :model="companyForm"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="企业名称" prop="companyName">
          <el-input
            v-model="companyForm.companyName"
            placeholder="请输入企业名称"
          />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input
            v-model="companyForm.creditCode"
            placeholder="请输入统一社会信用代码"
          />
        </el-form-item>
        <el-form-item label="营业执照图片" prop="businessLicense">
          <imageUpload v-model="companyForm.businessLicense" />
        </el-form-item>
        <el-form-item label="行业类型" prop="industry">
          <el-cascader
            v-model="companyForm.industry"
            :options="businessAreaData"
            :show-all-levels="false"
            @change="businessAreaChange"
          />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postCode">
          <el-input
            v-model="companyForm.postCode"
            max-length="6"
            placeholder="请输入邮政编码"
          />
        </el-form-item>
        <el-form-item label="经营状态" prop="businessStatus">
          <el-radio-group v-model="companyForm.businessStatus">
            <el-radio
              v-for="dict in this.getDictDatas(
                DICT_TYPE.COMPANY_BUSINESS_STATUS
              )"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="注册资本（万元）" prop="registeredCapital">
          <el-input
            v-model="companyForm.registeredCapital"
            type="number"
            placeholder="请输入注册资本"
          />
        </el-form-item>
        <el-form-item label="成立日期" prop="establishDate">
          <el-date-picker
            v-model="companyForm.establishDate"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择成立日期"
          />
        </el-form-item>
        <el-form-item label="法定代表人" prop="legalPerson">
          <el-input
            v-model="companyForm.legalPerson"
            placeholder="请输入法定代表人"
          />
        </el-form-item>
        <el-form-item label="子企业关系证明图片">
          <imageUpload
            v-model="companyForm.subCompanyRelationshipCertificatePicture"
          />
          <el-button type="text" @click="downloadFile">下载模版</el-button>
        </el-form-item>
        <el-form-item label="企业规模" prop="scale">
          <el-select v-model="companyForm.scale" placeholder="请输入企业规模">
            <el-option
              v-for="dict in this.getDictDatas(DICT_TYPE.ENTERPRISE_SCALE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业类型" prop="companyType">
          <el-select
            v-model="companyForm.companyType"
            placeholder="请选择企业状态"
          >
            <el-option
              v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册地址" required prop="provinceAndCity">
          <el-cascader
            v-model="companyForm.provinceAndCity"
            :options="provinceAndCityData"
            placeholder="请选择注册地址"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="registeredAddress">
          <el-input
            v-model="companyForm.registeredAddress"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="经营范围" prop="businessScope">
          <el-input
            v-model="companyForm.businessScope"
            type="textarea"
            placeholder="请输入经营范围"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backToUserForm">上一步</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看/编辑 -->
    <el-dialog
      :title="title"
      :visible.sync="openModefy"
      width="50%"
      append-to-body
    >
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="用户信息" name="userForm">
          <el-form
            ref="userForm"
            :model="userForm"
            :rules="rules"
            label-width="80px"
          >
            <el-form-item label="姓名" prop="applyUserName">
              <el-input
                v-model="userForm.applyUserName"
                :disabled="isCheck"
                placeholder="请输入姓名"
              />
            </el-form-item>
            <!-- 禁止修改手机号，因为编辑接口只改了企业，没有同步到用户，会引发问题，暂时不允许修改 -->
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                v-model="userForm.phoneNumber"
                :disabled="true"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item label="部门" prop="dept">
              <el-input
                v-model="userForm.dept"
                :disabled="isCheck"
                placeholder="请输入部门"
              />
            </el-form-item>
            <el-form-item label="职位" prop="job">
              <el-input
                v-model="userForm.job"
                :disabled="isCheck"
                placeholder="请输入职位"
              />
            </el-form-item>
            <el-form-item label="座机号" prop="tel">
              <el-input
                v-model="userForm.tel"
                :disabled="isCheck"
                placeholder="请输入座机号"
              />
            </el-form-item>
            <el-form-item label="邮箱号" prop="email">
              <el-input
                v-model="userForm.email"
                :disabled="isCheck"
                placeholder="请输入邮箱号"
              />
            </el-form-item>
            <el-form-item label="账户类型">
              <el-input disabled :value="userForm.roleType" />
            </el-form-item>
            <el-form-item label="是否白名单" prop="unrealFlag">
              <el-select v-model="userForm.unrealFlag" disabled>
                <el-option :value="0" label="否">否</el-option>
                <el-option :value="1" label="是">是</el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-row type="flex" class="row-bg" justify="end">
            <el-button
              v-if="!isCheck"
              type="primary"
              @click="modefyUserForm"
            >提交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="企业信息" name="second">
          <el-form
            ref="companyForm"
            :model="companyForm"
            :rules="rules"
            label-width="150px"
          >
            <el-form-item label="企业名称" prop="companyName">
              <el-input
                v-model="companyForm.companyName"
                :disabled="isCheck"
                placeholder="请输入企业名称"
              />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input
                v-model="companyForm.creditCode"
                :disabled="isCheck"
                placeholder="请输入统一社会信用代码"
              />
            </el-form-item>
            <el-form-item label="营业执照图片" prop="businessLicense">
              <imageUpload
                v-if="!isCheck"
                v-model="companyForm.businessLicense"
              />
              <img
                v-else
                v-imgError
                :src="companyForm.businessLicense"
                style="width: 146px; height: 146px"
                alt="营业执照"
              >
            </el-form-item>
            <el-form-item label="行业类型" prop="industry">
              <el-cascader
                v-model="companyForm.industry"
                :show-all-levels="false"
                :disabled="isCheck"
                :options="businessAreaData"
                @change="businessAreaChange"
              />
            </el-form-item>
            <el-form-item label="邮政编码" prop="postCode">
              <el-input
                v-model="companyForm.postCode"
                :disabled="isCheck"
                placeholder="请输入邮政编码"
              />
            </el-form-item>
            <el-form-item label="经营状态" prop="businessStatus">
              <el-radio-group
                v-model="companyForm.businessStatus"
                :disabled="isCheck"
              >
                <el-radio
                  v-for="dict in this.getDictDatas(
                    DICT_TYPE.COMPANY_BUSINESS_STATUS
                  )"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="注册资本（万元）" prop="registeredCapital">
              <el-input
                v-model="companyForm.registeredCapital"
                type="number"
                :disabled="isCheck"
                placeholder="请输入注册资本"
              />
            </el-form-item>
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                v-model="companyForm.establishDate"
                :disabled="isCheck"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择成立日期"
              />
            </el-form-item>
            <el-form-item label="法定代表人" prop="legalPerson">
              <el-input
                v-model="companyForm.legalPerson"
                :disabled="isCheck"
                placeholder="请输入法定代表人"
              />
            </el-form-item>
            <el-form-item label="子企业关系证明图片">
              <div v-if="!isCheck">
                <imageUpload
                  v-model="companyForm.subCompanyRelationshipCertificatePicture"
                />
                <el-button
                  type="text"
                  @click="downloadFile"
                >下载模版</el-button>
              </div>
              <img
                v-else
                v-imgError
                :src="companyForm.subCompanyRelationshipCertificatePicture"
                style="width: 146px; height: 146px"
                alt="子企业关系证明图片"
              >
            </el-form-item>
            <el-form-item label="企业规模" prop="scale">
              <el-select
                v-model="companyForm.scale"
                :disabled="isCheck"
                placeholder="请输入企业规模"
              >
                <el-option
                  v-for="dict in this.getDictDatas(DICT_TYPE.ENTERPRISE_SCALE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业类型" prop="companyType">
              <el-select
                v-model="companyForm.companyType"
                :disabled="isCheck"
                placeholder="请选择企业状态"
              >
                <el-option
                  v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="注册地址" required prop="provinceAndCity">
              <el-cascader
                v-model="companyForm.provinceAndCity"
                :options="provinceAndCityData"
                :disabled="isCheck"
                placeholder="请选择注册地址"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="registeredAddress">
              <el-input
                v-model="companyForm.registeredAddress"
                :disabled="isCheck"
                placeholder="请输入详细地址"
              />
            </el-form-item>
            <el-form-item label="经营范围" prop="businessScope">
              <el-input
                v-model="companyForm.businessScope"
                type="textarea"
                :disabled="isCheck"
                placeholder="请输入经营范围"
              />
            </el-form-item>
          </el-form>
          <el-row type="flex" class="row-bg" justify="end">
            <el-button
              v-if="!isCheck"
              type="primary"
              @click="modefyCompanyForm"
            >提交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyUser,
  createCompany,
  updateCompany,
  delUser,
  getCompanyUserInfo,
  getCompanyInfo,
  deleteCompanyUserInfo
} from '@/api/school-admin-api/userManage/company/index.js'
import { encryptDes } from '@/utils/crypto'
import ImageUpload from '@/components/ImageUpload'
import businessAreaData from '@/utils/businessAreaData.js'
import { deepClone } from '@/utils/index'
import moment from 'moment'
import {
  provinceAndCityData,
  getProvinceAndCityDataLabel,
  getProvinceAndCityDataValue
} from '@/utils/frontDataDict.js'
import { getUserCountByMobile } from '@/api/company-admin-api/userManage/index.js'
import { exportCompanyUser } from '@/api/company-admin-api/hireManage/index.js'
import { mapGetters } from 'vuex'

export default {
  name: 'Company',
  components: {
    ImageUpload
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      const phoneReg = /^[1][0-9]{10}$/
      if (value === '') {
        return callback(new Error('手机号不能为空'))
      } else {
        if (phoneReg.test(value)) {
          return callback()
        } else {
          return callback(new Error('格式有误'))
        }
      }
    }
    const validataEmail = (rule, value, callback) => {
      const emailReg =
        /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      } else {
        if (emailReg.test(value)) {
          return callback()
        } else {
          return callback(new Error('格式有误'))
        }
      }
    }
    return {
      // 企业行业类型数据，二级联动
      businessAreaData: businessAreaData,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业管理列表
      list: [],
      // 弹出层标题
      title: '',
      provinceAndCityData,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        nickname: null, // 申请人名称
        phoneNumber: null, // 手机号
        companyName: null, // 公司名称
        authorizedStatus: null, // 认证状态
        roleType: null // 账号类型
      },
      // 表单参数
      form: {
        applyUserName: undefined,
        phoneNumber: undefined,
        tel: undefined,
        email: undefined,
        dept: undefined,
        job: undefined,
        companyName: undefined,
        creditCode: undefined,
        businessLicense: undefined,
        industry: [],
        postCode: undefined,
        businessStatus: 'renew',
        registeredCapital: undefined,
        establishDate: '',
        legalPerson: undefined,
        scale: undefined,
        companyType: undefined,
        registeredAddress: undefined,
        businessScope: undefined,
        subCompanyRelationshipCertificatePicture: undefined
      },
      // 用户信息表
      userForm: {
        applyUserName: '', // 企业申请人姓名
        dept: '', // 部门
        job: '', // 职位
        tel: '', // 电话
        email: '', // 邮箱
        phoneNumber: '', // 手机号
        roleType: '',
        unrealFlag: 0 // 是否是白名单
      },
      // userForm: {
      //   applyUserName: "刘德华",
      //   dept: "业务部",
      //   job: "健身教练",
      //   tel: "075528899991",
      //   email: "1234@qq.com",
      //   phoneNumber: "18824236689",
      //   roleType: "企业管理员",
      // },
      // 企业信息表
      companyForm: {
        companyName: '', // 企业名称
        creditCode: '', // 统一信用代码
        businessLicense: '', // 营业执照
        industry: [], // 行业类型
        postCode: '', // 邮政编码
        businessStatus: 'renew', // 经营状态
        registeredCapital: '', // 注册资本
        establishDate: '', // 成立日期
        legalPerson: '', // 法人
        subCompanyRelationshipCertificatePicture: '', // 子母企业关系证明
        scale: '', // 企业规模
        companyType: '', // 企业类型
        provinceAndCity: '', // 注册地址
        registeredAddress: '', // 详细地址
        status: '-1', // -2 禁用 -1 启用 写死是-1
        businessScope: '', // 经营范围
        registerIp: '127.0.0.1' // 注册ip地址,写死，冗余字段
      },
      // 表单校验
      rules: {
        applyUserName: [
          {
            required: true,
            message: '企业申请人姓名不能为空',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        tel: [{ required: false, message: '座机号不能为空', trigger: 'blur' }],
        email: [{ required: true, validator: validataEmail, trigger: 'blur' }],
        dept: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
        job: [{ required: true, message: '职位不能为空', trigger: 'blur' }],
        companyName: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' }
        ],
        creditCode: [
          {
            required: true,
            message: '统一社会信用代码不能为空',
            trigger: 'blur'
          }
        ],
        businessLicense: [
          {
            required: true,
            message: '营业执照图片不能为空',
            trigger: 'blur'
          }
        ],
        industry: [
          {
            type: 'array',
            required: true,
            message: '行业类型不能为空',
            trigger: 'change'
          }
        ],
        postCode: [
          { required: false, message: '邮政编码不能为空', trigger: 'blur' }
        ],
        businessStatus: [
          { required: true, message: '经营状态不能为空', trigger: 'blur' }
        ],
        registeredCapital: [
          { required: true, message: '注册资本不能为空', trigger: 'blur' }
        ],
        establishDate: [
          { required: true, message: '成立日期不能为空', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法定代表人不能为空', trigger: 'blur' }
        ],
        scale: [
          { required: true, message: '企业规模不能为空', trigger: 'change' }
        ],
        companyType: [
          { required: true, message: '企业类型不能为空', trigger: 'change' }
        ],
        provinceAndCity: [
          { required: true, message: '注册地址不能为空', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        businessScope: [
          { required: true, message: '经营范围不能为空', trigger: 'blur' }
        ],
        subCompanyRelationshipCertificatePicture: [
          {
            required: false,
            message: '子企业关系证明图片不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 企业单独修改时，接口的数据格式
      baseCompanyForm: {
        applyUserName: '',
        phoneNumber: '',
        tel: '',
        email: '',
        dept: '',
        job: '',
        companyName: '',
        creditCode: '',
        businessLicense: '',
        industryType: '',
        postCode: '',
        businessStatus: '',
        registeredCapital: '',
        establishDate: null,
        legalPerson: '',
        scale: '',
        status: '',
        authorizedStatus: '',
        companyType: '',
        companyPicture: '',
        registeredAddress: '',
        businessScope: '',
        companyShortName: null,
        companyLogo: null,
        industry: '',
        introduction: null,
        environment: '[]',
        companyAddress: '',
        companyCoordinate: '',
        subCompanyRelationshipCertificatePicture: '',
        subCompanyRelationshipCertificateWord: '',
        topStatus: null,
        tenantId: null,
        userId: null,
        companyId: null,
        id: null,
        createTime: null
      },
      openUserDialog: false, // 新建-用户信息弹窗
      openCompanyDialog: false, // 新建-企业信息弹窗
      openCompanyWhite: false, // 是否创建的是白名单企业
      openModefy: false, // 查看/编辑 弹窗
      activeName: 'userForm',
      isCheck: false, // 是否为查看模式，true 时打开查看弹窗，不可修改企业用户数据
      isCreate: false, // 是否为新建模式
      authStatus: {
        authorized: '已认证',
        unauthorized: '未认证',
        reject: '认证被驳回'
      }
    }
  },
  computed: {
    ...mapGetters(['roles']),
    isSuperAdmin() {
      return (
        Array.isArray(this.roles) && this.roles.indexOf('super_admin') > -1
      )
    }
  },
  created() {
    this.getList()
  },
  methods: {
    exportDate() {
      // 处理查询参数
      const params = {}
      for (const key in this.queryParams) {
        if (this.queryParams[key] !== null) {
          params[key] = this.queryParams[key]
        }
      }
      if (params.phoneNumber) {
        params.phoneNumber = encryptDes(params.phoneNumber)
      }
      exportCompanyUser(params).then((response) => {
        this.$download.excel(response, '企业用户信息.xls')
      })
    },
    // 单独修改用户信息
    modefyUserForm() {
      console.log('单独修改用户信息')
      this.modefyCompanyForm()
    },
    // 单独修改企业信息
    modefyCompanyForm() {
      this.$refs.companyForm.validate((boo) => {
        if (boo) {
          const param = Object.assign({}, this.baseCompanyForm)
          for (const key in this.companyForm) {
            if (
              this.companyForm[key] !== null &&
              this.companyForm[key] !== ''
            ) {
              param[key] = this.companyForm[key]
            }
          }
          // 企业数据更新，要带上用户数据
          for (const key in this.userForm) {
            if (
              this.userForm[key] !== null &&
              this.userForm[key] !== ''
            ) {
              param[key] = this.userForm[key]
            }
          }
          param.industry = JSON.stringify(param.industry)
          param.industryType = param.industry
          param.city = getProvinceAndCityDataLabel(param.provinceAndCity)
          param.province = getProvinceAndCityDataLabel(
            param.provinceAndCity,
            3
          )
          updateCompany(param).then((res) => {
            if (res.code === 0 && res.data) {
              this.$message.success('更新企业信息成功')
              this.cancel()
            }
          })
        }
      })
    },
    // 下载子企业关系证明模版
    downloadFile() {
      window.open('https://www.baidu.com/aaa/p1.pgn')
    },
    // 企业行业类型修改
    businessAreaChange(value) {
      this.companyForm.industry = value
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 处理查询参数
      const params = {}
      for (const key in this.queryParams) {
        if (this.queryParams[key] !== null) {
          params[key] = this.queryParams[key]
        }
      }
      if (params.phoneNumber) {
        params.phoneNumber = encryptDes(params.phoneNumber)
      }
      // 执行查询
      getCompanyUser(params).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    // 新建-提交用户信息
    submitUserForm() {
      this.$refs.userForm.validate((boo) => {
        if (boo) {
          const params = {
            mobile: this.userForm.phoneNumber
          }
          getUserCountByMobile(params).then(res => {
            if (res && res.data === 0) {
              this.openUserDialog = false
              this.openCompanyWhite && (this.userForm.unrealFlag = 1)
              this.openCompanyDialog = true
            } else {
              this.$message.warning('当前手机号已存在企业，请重新填写手机号')
            }
          })
        }
      })
    },
    // 新增，返回上一步
    backToUserForm() {
      this.openUserDialog = true
      this.openCompanyDialog = false
    },
    //  创建新公司，打开空弹窗
    createNewCompany(type = false) {
      this.reset() // 清除数据
      this.isCreate = true // 创建模式
      this.isCheck = false
      this.openCompanyDialog = false
      this.openUserDialog = true
      console.log(type)
      this.title = type ? '新建白名单企业' : '新建企业'
      this.openCompanyWhite = type
    },
    /** 取消按钮 */
    cancel() {
      this.openUserDialog = false
      this.openCompanyWhite = false
      this.openCompanyDialog = false
      this.openModefy = false
      this.activeName = 'userForm'
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = this.$options.data().form
      this.userForm = this.$options.data().userForm
      this.companyForm = this.$options.data().companyForm
      this.resetForm('form')
      this.resetForm('userForm')
      this.resetForm('companyForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.openUserDialog = true
      this.title = '新建企业用户'
    },
    /**
     * 打开企业详情页面，用户详情、企业详情通过接口获取
     * @param {*} row
     */
    handleCheck(row) {
      this.isCheck = true
      this.companyId = row.companyId
      this.userId = row.userId
      getCompanyUserInfo({
        userId: this.userId,
        companyId: this.companyId
      }).then((res) => {
        if (res.code === 0 && res.data) {
          res.data.establishDate =
            typeof res.data.establishDate === 'number'
              ? moment(res.data.establishDate).format('yyyy-MM-DD')
              : ''
          for (const key in res.data) {
            if (Object.hasOwnProperty.call(this.userForm, key)) {
              this.userForm[key] = deepClone(res.data[key])
            }
            if (Object.hasOwnProperty.call(this.companyForm, key)) {
              this.companyForm[key] = deepClone(res.data[key])
            }
          }

          try {
            res.data.city &&
              res.data.province &&
              (this.companyForm.provinceAndCity =
                getProvinceAndCityDataValue(
                  res.data.province + res.data.city
                ) || '')
          } catch {
            () => {}
          }
          this.companyForm.industry = JSON.parse(this.companyForm.industry)
          this.title = '查看企业'
          setTimeout(() => {
            this.openModefy = true
          })
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isCheck = false
      const { companyId, userId } = row
      getCompanyInfo({ id: companyId }).then((res) => {
        if (res.code === 0 && res.data) {
          this.baseCompanyForm = res.data // 备份需要提交的企业数据，后面直接覆盖提交
          getCompanyUserInfo({
            userId: userId,
            companyId: companyId
          }).then((res) => {
            if (res.code === 0 && res.data) {
              res.data.establishDate =
                typeof res.data.establishDate === 'number'
                  ? moment(res.data.establishDate).format('yyyy-MM-DD')
                  : ''
              for (const key in res.data) {
                if (Object.hasOwnProperty.call(this.userForm, key)) {
                  this.userForm[key] = deepClone(res.data[key])
                }
                if (Object.hasOwnProperty.call(this.companyForm, key)) {
                  this.companyForm[key] = deepClone(res.data[key])
                }
              }

              try {
                res.data.city &&
                  res.data.province &&
                  (this.companyForm.provinceAndCity =
                    getProvinceAndCityDataValue(
                      res.data.province + res.data.city
                    ) || '')
              } catch {
                () => {}
              }
              this.companyForm.industry = JSON.parse(this.companyForm.industry)
              this.title = '编辑企业'
              setTimeout(() => {
                this.openModefy = true
              })
            }
          })
        }
      })
    },
    /** 新建企业用户的提交 */
    submitForm() {
      this.$refs.companyForm.validate((boo) => {
        if (boo) {
          const params = Object.assign(
            {},
            this.form,
            this.userForm,
            this.companyForm
          )
          params.industry = JSON.stringify(params.industry)
          params.industryType = params.industry
          params.city = getProvinceAndCityDataLabel(params.provinceAndCity)
          params.province = getProvinceAndCityDataLabel(
            params.provinceAndCity,
            3
          )
          for (const key in params) {
            if (params[key] === null || params[key] === '') {
              delete params[key]
            }
          }
          // 修改的提交
          if (this.isCreate) {
            // 添加的提交
            createCompany(params).then((response) => {
              this.$modal.msgSuccess('新增企业用户成功')
              this.openCompanyDialog = false
              this.getList()
            })
          } else {
            updateCompany(params).then((response) => {
              this.$modal.msgSuccess('修改企业用户成功')
              this.openCompanyDialog = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    /**
     * 删除用户操作
     * 如果该企业用户不是管理员，调用用户删除接口，
     * 如果该用户是企业管理员，调用企业删除接口，并给出提示
     * @param {} row
     */
    handleDelete(row) {
      const { userId, companyId } = row
      if (
        row.roleType === '企业管理员' ||
        row.roleType === '租户管理员' ||
        row.roleType === 'tenant_admin'
      ) {
        this.$modal
          .confirm('该用户是企业管理员，若删除，则整个企业也会被删除，确定吗？')
          .then(function() {
            // return deleteCompany({ id: companyId });
            return deleteCompanyUserInfo({ userId, companyId })
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {})
      } else {
        this.$modal
          .confirm('确定删除该用户吗？')
          .then(function() {
            return delUser(userId)
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {})
      }
    }
  }
}
</script>
